<?php
namespace app\houtai\controller\user;
use app\houtai\controller\BaseController;
use think\db\Expression;
use org\GoApi\FamilyCtrl;

class FamilyController extends BaseController {
  /**
   *  @brief  : 家园绑定查询
   *  @return : page|JSON
   *  @details: 
   */
  public function indexAction() {
    $conds = ['a.Status' => 1, 'b.State' => 1];
    $order = [];
    $GAME_KIND  = GetGameKind();
    $CHANNELS   = $this->GetAdminChannel();
    ////////////////////////////////////////////////////////////////////////////
    $channel = $this->request->param('channel/d', -1);
    if ($channel > 0 && array_key_exists($channel, $CHANNELS)) {
      $conds['c.Channel'][] = ['IN', array_keys($CHANNELS)];
      $conds['c.Channel'][] = ['EQ', $channel];
    } else {
      $conds['c.Channel'] = ['IN', array_keys($CHANNELS)];
    }
    //////////////////////////////////////////////////////
    $kind = $this->request->param('kind/d', -1);
    if ($kind > 0 && array_key_exists($kind, $GAME_KIND)) {
      $conds['b.KindID'] = $kind;
    }
    //////////////////////////////////////////////////////

    $black = $this->request->param('black/d', -1); // 是否在黑名单
    if ($black >= 0 && in_array($black, [0, 1])) {
      $conds['a.IsBlack'] = $black;
    }

    //////////////////////////////////////////////////////
    $search = $this->request->param('search/s', '', 'trim');
    if (!empty($search)) {
      if (is_numeric($search)) {
        $search = $this->request->param('search/d', 0);
        $conds['a.MemberUID|c.GameID'] = $search;
      } else {
        $conds['c.NickName'] = ['LIKE', "%{$search}%"];
      }
    }
    //////////////////////////////////////////////////////
    $code1 = $this->request->param('code1/d', 0);
    if ($code1 > 0) {
      $conds['b.Code'] = $code1;  // 六位群号
    }
    $code2 = $this->request->param('code2/d', 0); // 所属推广员邀请码
    if ($code2 > 0) {
      $conds['g.GameID'] = $code2;
    }
    $code3 = $this->request->param('code3/d', 0); // 群主GameID
    if ($code3 > 0) {
      $conds['e.GameID'] = $code3;
    }
      $code4 = $this->request->param('code4/d', 0); // 群号
      if ($code4 > 0) {
          $conds['b.Code'] = $code4;
      }
    //////////////////////////////////////////////////////
    $orderMap = [
      'A' => 'ID',
      'B' => 'Channel',
      'C' => 'KindID',
      'D' => 'Code',
      'E' => 'GameID',
      'F' => 'AGameID',
      'G' => 'FGameID',
      'H' => 'CreateTime',
      'I' => 'UpdateTime',
    ];
    $this->orderField = array_key_exists($this->orderField, $orderMap) ? $this->orderField : 'G';
    $order[$orderMap[$this->orderField]] = $this->orderDirection;
    $codes['a.Code'] = $code1;
    ////////////////////////////////////////////////////////////////////////////
    $list = table('CYWebSMSDB.dbo.FamilyMember a', 'rydb.websms')->field([
      'a.ID', 'a.MemberUID' => 'UserID', 'a.UserRight', 'a.IsBlack', 'a.IsPass',
      'a.CreateTime', 'a.UpdateTime', 'a.UserRight', 'b.AUID' => 'FUserID', 'a.Gold',
      'b.Code', 'b.KindID', 'c.GameID', 'c.NickName', 'c.Sex','b.FamilyType',
      'c.AccountsType', 'c.Channel', "ISNULL(c.AccountImgUrl, '')" => 'Avatar',
      'c.Accounts', 'c.Compellation', 'c.PassPortID', 'c.RegisterMobile', 'c.RegisterDate',
      'c.RegisterIP', 'c.GameLogonCount', 'c.LastLogonDate', 'c.LastLogonIP',
      'e.GameID' => 'FGameID', 'e.AccountsType' => 'FAccountsType',
      '(CASE WHEN LEN([e].[Compellation]) = 0 THEN [e].[NickName] ELSE [e].[Compellation] END)'=>'FCompellation',
      'ISNULL(e.SpreaderID, 0)' => 'AUserID', 'ISNULL(g.GameID, 0)' => 'AGameID',
      "ISNULL(g.Compellation, '')" => 'ACompellation', "ISNULL(g.AccountImgUrl, '')" => 'AAvatar',
      'ISNULL(g.AccountsType, 0)' => 'AAccountsType', "ISNULL(e.AccountImgUrl, '')" => 'FAvatar',
      '(CASE WHEN a.MemberUID = b.AUID THEN 1 ELSE 0 END)' => 'IsBoss',
    ])
    ->join('CYWebSMSDB.dbo.Family b', 'b.ID = a.FamilyID', 'LEFT')
    // 成员
    ->join('CYBasicDB.dbo.AccountsInfo c', 'c.UserID = a.MemberUID', 'LEFT')
    // 群主
    ->join('CYBasicDB.dbo.AccountsInfo e', 'e.UserID = b.AUID AND e.Channel = c.Channel', 'LEFT')
    // 
    ->join('CYBasicDB.dbo.ChannelConfig k', 'k.ID = c.Channel', 'LEFT')
    ->join('CYBasicDB.dbo.AccountsGameCurrency f', 'f.UserID = a.MemberUID', 'LEFT')
    // 代理
    ->join('CYBasicDB.dbo.AccountsInfo g', 'g.UserID = c.SpreaderID', 'LEFT')
    ->where($conds)->order($order)->paginate();
    ////////////////////////////////////////////////////////////////////////////
    return $this->fetch('', [
      'CHANNELS'  => $CHANNELS,
      'channel'   => $channel,
      'GAME_KIND' => $GAME_KIND,
      'kind'    => $kind,
      'code1'   => $code1 === 0 ? -1 : $code1,
      'code2'   => $code2 === 0 ? '' : $code2,
      'code3'   => $code3 === 0 ? '' : $code3,
      'list'    => $list,
      'search'  => $search,
      'black'   => $black,
    ]);
  }
  /**
   *  @brief  : 家园绑定统计
   *  @return : page
   *  @details: 
   */
  public function trendAction() {

    $order = [];
    $STATES   = [0 => '待审核', 1 => '已审核', 2 => '已退回'];
    $GAME_KIND  = GetGameKind();
    $FAMILYTYPE = GetFamilyType();
    $CHANNELS   = $this->GetAdminChannel();
    ////////////////////////////////////////////////////////////////////////////
    $channel = $this->request->param('channel/d', -1);
    $familytype = $this->request->param('FamilyType/d', -1);
    if ($familytype > 0){
        $conds['a.FamilyType']  = $familytype;
    }
    $conds['a.FamilyType']  = ['NEQ',2];
    if ($channel > 0 && array_key_exists($channel, $CHANNELS)) {
      $conds['b.Channel'][] = ['IN', array_keys($CHANNELS)];
      $conds['b.Channel'][] = ['EQ', $channel];
    } else {
      $conds['b.Channel'] = ['IN', array_keys($CHANNELS)];
    }
    $kind = $this->request->param('kind/d', -1);
    $kind = array_key_exists($kind, $GAME_KIND) ? $kind : -1;
    if ($kind > 0) {
      $conds['a.KindID'] = $kind;
    }
    $state = $this->request->param('state/d', -1);
    $state = array_key_exists($state, $STATES) ? $state : -1;
    if ($state >= 0) {
      $conds['a.State'] = $state;
    }
    //////////////////////////////////////////////////////
    $search = $this->request->param('search/d', 0);
    if ($search > 0) {
      $conds['a.Code|b.GameID|a.AUID'] = $search;
    }
    //////////////////////////////////////////////////////
    $orderMap = [
      'A' => 'ID',
      'B' => 'Channel',
      'C' => 'KindID',
      'D' => 'Code',
      'E' => 'Caption',
      'F' => 'GameID',
      'G' => 'TotalMem',
      'H' => 'TotalBlack',
      'K' => 'State',
      'L' => 'UpdateTime',
    ];
    $this->orderField = array_key_exists($this->orderField, $orderMap) ? $this->orderField : 'L';
    $order[$orderMap[$this->orderField]] = $this->orderDirection;
    //////////////////////////////////////////////////////
    $list = table('CYWebSMSDB.dbo.Family a', 'rydb.websms')->field([
      'a.*', 'b.GameID', 'b.Sex', 'b.AccountsType',
      'c.Total' => 'TotalMem', 'f.Total' => 'TotalBlack', 'b.AccountImgUrl',
      'd.AutoFamily', '(CASE WHEN LEN([b].[Compellation])>0 THEN [b].[Compellation] ELSE [b].[NickName] END )' => 'NickName',
    ])
    ->join('CYBasicDB.dbo.AccountsInfo b', 'b.UserID = a.AUID', 'LEFT')
    ->join('(SELECT FamilyID, COUNT (ID) AS Total FROM CYWebSMSDB.dbo.FamilyMember WHERE Status = 1 AND IsBlack = 0 GROUP BY FamilyID) c', 'c.FamilyID = a.ID', 'LEFT')
    ->join('(SELECT FamilyID, COUNT (ID) AS Total FROM CYWebSMSDB.dbo.FamilyMember WHERE Status = 1 AND IsBlack = 1 GROUP BY FamilyID) f', 'f.FamilyID = a.ID', 'LEFT')
    ->join('CYWebSMSDB.dbo.AgentReg d', 'd.UserID = a.AUID', 'LEFT')
    ->where($conds)->order($order)->paginate();
    // echo  table('RYWebSMSDB.dbo.Family a', 'rydb.websms')->getLastSql();die;
    ////////////////////////////////////////////////////////////////////////////
    $GroupID = [];
    foreach($list->items() as $item) {
      if ($item['Code'] > 0) {
        $GroupID[] = $item['Code'];
      }
    }
    $RangeScore = [];
    if (!empty($GroupID)) {
      $data = FamilyCtrl::Find($GroupID);
      if (!empty($data['Data'])) {
        $data = $data['Data'];
        foreach($data as & $item) {
          $GroupID = $item['GameID'];
          unset($item['GameID']);
          $RangeScore[$GroupID] = $item;
        }
      }
    }
    ////////////////////////////////////////////////////////////////////////////
    return $this->fetch('', [
      'CHANNELS'  => $CHANNELS,
      'GAME_KIND' => $GAME_KIND,
      'STATES'    => $STATES,
      'channel'   => $channel,
      'FamilyType'=> $FAMILYTYPE,
      'kind'      => $kind,
      'state'     => $state,
      'search'    => $search === 0 ? '' : $search,
      'list'      => $list,
      'RangeScore'=> $RangeScore,
    ]);
  }
    /**
     * 亲友团成员查询
     * */
  public function FamilyAction(){
      $conds = ['a.Status' => 1, 'b.State' => 1];
      $order = [];
      $GAME_KIND  = GetGameKind();
      $CHANNELS   = $this->GetAdminChannel();
      ////////////////////////////////////////////////////////////////////////////
      $channel = $this->request->param('channel/d', -1);
      if ($channel > 0 && array_key_exists($channel, $CHANNELS)) {
          $conds['c.Channel'][] = ['IN', array_keys($CHANNELS)];
          $conds['c.Channel'][] = ['EQ', $channel];
      } else {
          $conds['c.Channel'] = ['IN', array_keys($CHANNELS)];
      }
      //////////////////////////////////////////////////////
      $kind = $this->request->param('kind/d', -1);
      if ($kind > 0 && array_key_exists($kind, $GAME_KIND)) {
          $conds['b.KindID'] = $kind;
      }
      //////////////////////////////////////////////////////

      $black = $this->request->param('black/d', -1); // 是否在黑名单
      if ($black >= 0 && in_array($black, [0, 1])) {
          $conds['a.IsBlack'] = $black;
      }

      //////////////////////////////////////////////////////
      $search = $this->request->param('search/s', '', 'trim');
      if (!empty($search)) {
          if (is_numeric($search)) {
              $search = $this->request->param('search/d', 0);
              $conds['a.MemberUID|c.GameID'] = $search;
          } else {
              $conds['c.NickName'] = ['LIKE', "%{$search}%"];
          }
      }
      //////////////////////////////////////////////////////
      $code1 = $this->request->param('code1/d', 0);
      if ($code1 > 0) {
          $conds['b.Code'] = $code1;  // 六位群号
      }
      $code2 = $this->request->param('code2/d', 0); // 所属推广员邀请码
      if ($code2 > 0) {
          $conds['g.GameID'] = $code2;
      }
      $code3 = $this->request->param('code3/d', 0); // 群主GameID
      if ($code3 > 0) {
          $conds['e.GameID'] = $code3;
      }
      //////////////////////////////////////////////////////
      $orderMap = [
          'A' => 'ID',
          'B' => 'Channel',
          'C' => 'KindID',
          'D' => 'Code',
          'E' => 'GameID',
          'F' => 'AGameID',
          'G' => 'FGameID',
          'H' => 'CreateTime',
          'I' => 'UpdateTime',
      ];
      $this->orderField = array_key_exists($this->orderField, $orderMap) ? $this->orderField : 'G';
      $order[$orderMap[$this->orderField]] = $this->orderDirection;
      $codes['a.Code'] = $code1;
      $auid = table('Family a', 'rydb.websms')->where($codes)->find();
      $map['AUID'] = ['eq',$auid['AUID']];

      $familycode = table('Family', 'rydb.websms')->field(['ID','AUID','Code','Caption'])->where($map)->select();
      ////////////////////////////////////////////////////////////////////////////
      $list = table('CYWebSMSDB.dbo.FamilyMember a', 'rydb.websms')->field([
          'a.ID', 'a.MemberUID' => 'UserID', 'a.UserRight', 'a.IsBlack', 'a.IsPass',
          'a.CreateTime', 'a.UpdateTime', 'a.UserRight', 'b.AUID' => 'FUserID', 'a.Gold',
          'b.Code', 'b.KindID', 'c.GameID', 'c.NickName', 'c.Sex',
          'c.AccountsType', 'c.Channel', "ISNULL(c.AccountImgUrl, '')" => 'Avatar',
          'c.Accounts', 'c.Compellation', 'c.PassPortID', 'c.RegisterMobile', 'c.RegisterDate',
          'c.RegisterIP', 'c.GameLogonCount', 'c.LastLogonDate', 'c.LastLogonIP',
          'e.GameID' => 'FGameID', 'e.AccountsType' => 'FAccountsType',
          '(CASE WHEN LEN([e].[Compellation]) = 0 THEN [e].[NickName] ELSE [e].[Compellation] END)'=>'FCompellation',
          'ISNULL(h.SpreaderID, 0)' => 'AUserID', 'ISNULL(g.GameID, 0)' => 'AGameID',
          "ISNULL(g.Compellation, '')" => 'ACompellation', "ISNULL(g.AccountImgUrl, '')" => 'AAvatar',
          'ISNULL(g.AccountsType, 0)' => 'AAccountsType', "ISNULL(e.AccountImgUrl, '')" => 'FAvatar',
          '(CASE WHEN a.MemberUID = b.AUID THEN 1 ELSE 0 END)' => 'IsBoss',
      ])
          ->join('CYWebSMSDB.dbo.Family b', 'b.ID = a.FamilyID', 'LEFT')
          // 成员
          ->join('CYBasicDB.dbo.AccountsInfo c', 'c.UserID = a.MemberUID', 'LEFT')
          // 群主
          ->join('CYBasicDB.dbo.AccountsInfo e', 'e.UserID = b.AUID AND e.Channel = c.Channel', 'LEFT')
          //
          ->join('CYBasicDB.dbo.ChannelConfig k', 'k.ID = c.Channel', 'LEFT')
          ->join('CYBasicDB.dbo.AccountsGameCurrency f', 'f.UserID = a.MemberUID', 'LEFT')
          ->join('CYBasicDB.dbo.AccountsInfo h','h.UserID=f.UserID','LEFT')
          // 代理
          ->join('CYBasicDB.dbo.AccountsInfo g', 'g.UserID = h.SpreaderID', 'LEFT')
          ->where($conds)->order($order)->paginate();
      ////////////////////////////////////////////////////////////////////////////
      return $this->fetch('', [
          'CHANNELS'  => $CHANNELS,
          'channel'   => $channel,
          'GAME_KIND' => $GAME_KIND,
          'title'   =>$auid,
          'kind'    => $kind,
          'code1'   => $code1 === 0 ? '' : $code1,
          'code2'   => $code2 === 0 ? '' : $code2,
          'code3'   => $code3 === 0 ? '' : $code3,
          'list'    => $list,
          'familycode' => $familycode,
          'search'  => $search,
          'black'   => $black,
      ]);
  }


  /**
   *  @brief  : 更新群标题
   *  @return : JSON
   *  @details: 
   */
  public function UpdateCaptionAction() {
    if (!$this->request->isPost()) {
      return result([], 1, '非法请求');
    }
    $FamilyID = $this->request->param('FamilyID/d', 0);
    $Caption = $this->request->param('Caption/s', '');
    $eax = strlen($Caption);
    if ($FamilyID <= 0 || $eax <= 0 || $eax >= 255) {
      return result([], 2, '业务参数非法');
    }
    $eax = table('Family', 'rydb.websms')->where(['ID' => $FamilyID])->update([
      'Caption'     => $Caption,
      'UpdateTime'  => new Expression('GETDATE()'),
    ]);
    return result([], 0);
  }
  /**
   *  @brief  : 自动同步家园
   *  @return : JSON
   *  @details: 
   */
  public function autoAction() {
    if (!$this->request->isPost()) {
      return result([], 1, '非法请求');
    }
    $auid = $this->request->param('auid/d', 0);
    if ($auid <= 0) {
      return result([], 2, '业务参数非法');
    }
    $agent = table('AgentReg', 'rydb.websms')->where('UserID', $auid)->find();
    if (empty($agent)) {
      return result([], 3, '推广员不存在');
    }
    $chk = $this->request->param('chk/d', 0);
    $chk = $chk > 0 ? 1 : 0;
    table('AgentReg', 'rydb.websms')->where('UserID', $auid)->setField('AutoFamily', $chk);
    return result([], 0);
  }
  /**
   *  @brief  : 添加群成员
   *  @return : JSON
   *  @details: 
   */
  public function MemberAddAction() {
    if (!$this->request->isPost()) {
      return result([], 1, '非法请求');
    }
    $FamilyID = $this->request->param('FamilyID/d', 0);
    $GamesID = $this->request->param('GameID', 0);
    $GameID = explode(',',$GamesID);
    if ($FamilyID <= 0 || count($GameID) <= 0) {
      return result([], 2, '业务参数非法');
    }
    $AUID = table('Family', 'rydb.websms')->where(['ID' => $FamilyID])->value('AUID');
    if ($AUID <= 0) {
      return result([], 3, '群不存在');
    }
    // 群主为玩家或代理
    $Boss = table('AccountsInfo', 'rydb.basic')->where(['UserID' => $AUID])->find();
    if (empty($Boss)) {
      return result([], 4, '群主不存在');
    }
    foreach ($GameID as $val){
        $User[] = table('AccountsInfo', 'rydb.basic')->where(['GameID' => $val,'AccountsType'=>['NEQ',1]])->find();
        if (table('AccountsInfo', 'rydb.basic')->where(['GameID' => $val,'AccountsType'=>['EQ',1]])->find()){
            return result([], 5, '玩家'.$val.'不存在');
        }
    }
    foreach ($User as $va) {
        if ($Boss['Channel'] != $va['Channel']) {
            return result([], 6, "玩家[{$va['GameID']}]的渠道[{$va['Channel']}]和群主[{$Boss['GameID']}]的渠道[{$Boss['Channel']}]不一致, 加入失败");
        }

    }
    for($i=0;$i<count($User);$i++){
        if (table('FamilyMember', 'rydb.websms')->where(['FamilyID' => $FamilyID, 'MemberUID' => $User[$i]['UserID']])->count() > 0) {
                table('FamilyMember', 'rydb.websms')->where(['FamilyID' => $FamilyID, 'MemberUID' => $User[$i]['UserID']])->update([
                    'Status' => 1, 'IsPass' => 1, 'UpdateTime' => new Expression('GETDATE()'),
                ]);
        } else {
            table('FamilyMember', 'rydb.websms')->insert([
                'FamilyID'  => $FamilyID,
                'MemberUID' => $User[$i]['UserID'],
                'Status'    => 1,
                'IsPass'    => 1,
                'CreateTime'=> new Expression('GETDATE()'),
                'UpdateTime'=> new Expression('GETDATE()'),
            ]);
        }
    }
    return result([], 0);
  }
  /**
   *  @brief  : 删除群成员
   *  @return : JSON
   *  @details: 
   */
  public function MemberDeleteAction() {
    if (!$this->request->isPost()) {
      return result([], 100, '非法请求');
    }
    $id = $this->request->param('id/d', 0);
    if ($id <= 0) {
      return result([], 101, '业务输入有误');
    }
    $fmid = table('FamilyMember', 'rydb.websms')->where('ID', $id)->value('ID');
    if ($fmid <= 0) {
      return result([], 102, '绑定关系不存在');
    }

    $FM = table('FamilyMember', 'rydb.websms')->where('ID', $id)->find();
    $BS = table('Family', 'rydb.websms')->where('ID', $FM['FamilyID'])->find();
    if ($FM['MemberUID'] == $BS['AUID']) {
      return result([], 103, '群主不能删');
    }
    
    table('FamilyMember', 'rydb.websms')->where('ID', $id)->update([
      'Status' => 0, 'IsBlack' => 0, 'IsPass' => 0, 'UserRight' => 0,
      'UpdateTime' => new Expression('GETDATE()'),
    ]);
    return result([], 0);
  }
  /**
   *  @brief  : 群成员设置
   *  @return : page|JSON
   *  @details: 
   */
  public function mrightAction() {
    $id = $this->request->param('id/d', 0);
    $type = $this->request->param('type/d', 0);
    if ($this->request->isGet()) {
      if ($id <= 0) {
        return abort(1, '业务参数非法');
      }
      if ($type == 2) {
          $row = table('UnionMember A', 'rydb.websms')->where('ID', $id)->find();
          $row['RuleNumb'] = $row['UnionRuleNumb'];
      }else{
          $row = table('FamilyMember A', 'rydb.websms')->where('ID', $id)->find();
      }
      
      if (empty($row)) {
        return abort(2, '绑定关系不存在');
      }

      return $this->fetch('', ['row' => $row]);
    }
    if ($this->request->isPost()) {
      if ($id > 0) {
        $ur = $this->request->param('UserRight/a', []);
        $UserRight = 0;
        foreach($ur as $key=>$val) {
          $eax = 1;
          $eax<<=$key;
          $UserRight |= $eax;
        }
        $IsBlack = $this->request->param('IsBlack/d', 0);
        $IsBlack = $IsBlack > 0 ? 1 : 0;
        
        if ($IsBlack && $UserRight & 1 << 6) {
          return result([], 2, '该用户不能进小黑屋');
        }
        $RuleNumb = $this->request->param('RuleNumb/d', 0);
        $RuleNumb = $RuleNumb > 0 ? $RuleNumb : 5;   
        if ($type == 2) { //大联盟
          table('UnionMember', 'rydb.websms')->where('ID', $id)->update([
          'UserRight'   => $UserRight,
          'IsBlack'     => $IsBlack,
          'UnionRuleNumb'    => $RuleNumb,
          'UpdateTime'  => new Expression('GETDATE()'),
          ]);
        }else{ ///亲友团
          table('FamilyMember', 'rydb.websms')->where('ID', $id)->update([
          'UserRight'   => $UserRight,
          'IsBlack'     => $IsBlack,
          'RuleNumb'    => $RuleNumb,
          'UpdateTime'  => new Expression('GETDATE()'),
        ]);
        }
        
      }
      return result([], 0);
    }
  }
  /**
   *  @brief  : 群审核通过
   *  @return : JSON
   *  @details: 
   */
  public function agreeAction() {
    if (!$this->request->isPost()) {
      return result([], 1, '非法请求');
    }
    $id = $this->request->param('id/d', 0);
    if ($id <= 0) {
      return result([], 2, '业务参数非法');
    }
    $family = table('Family', 'rydb.websms')->where(['ID' => $id])->find();

    if (empty($family)) {
      return result([], 3, '欲处理的数据不存在');
    }
    if ($family['State']==1) {
      return result([], 4, '欲处理的群已审核');
    }
    if ($family['Code'] > 0) {
      return result([], 5, '欲处理的群已分配群号');
    }
    $code = table('CodeIdentifier', 'rydb.websms')->where(['FamilyUsed' => 0])->order('ID')->find();
    if (empty($code)) {
      return result([], 6, '系统分配六位群标识失败');
    }
    $eax = table('Family', 'rydb.websms')->where(['ID' => $family['ID']])->update([
      'Code'  => $code['Code'],
      'State' => 1,
      'UpdateTime'  => new Expression('GETDATE()'),
    ]);
    table('CodeIdentifier', 'rydb.websms')->where(['ID' => $code['ID']])->setField('FamilyUsed', $family['ID']);
    $member = table('FamilyMember', 'rydb.websms')->where(['FamilyID' => $family['ID'], 'MemberUID' => $family['AUID']])->find();
    //判断申请的群类型，1=房卡，2=大联盟
    if ($member['FamilyTYpe'] == 1) {
      $RuleNumb = 5;
      $UnionRuleNumb = 0;
    }elseif($member['FamilyTYpe'] == 2){
      $RuleNumb = 0;
      $UnionRuleNumb = 5;
    }
    if (empty($member)) {
      $eax = table('FamilyMember', 'rydb.websms')->insert(['FamilyID' => $family['ID'], 'MemberUID' => $family['AUID'], 'Status' => 1, 'IsPass' => 1,'RuleNumb'=>$RuleNumb,'UnionRuleNumb'=>$UnionRuleNumb]);
    } else {
      $eax = table('FamilyMember', 'rydb.websms')->where(['ID' => $member['ID']])->update(['Status' => 1, 'IsPass' => 1, 'UpdateTime' => new Expression('GETDATE()'),'RuleNumb'=>$RuleNumb,'UnionRuleNumb'=>$UnionRuleNumb]);
    }
    return result([], 0);
  }
  /**
   *  @brief  : 成员加入群审核通过
   *  @return : JSON
   *  @details: 
   */
  public function agreemAction() {
    if (!$this->request->isPost()) {
      return result([], 1, '非法请求');
    }
    $id = $this->request->param('id/d', 0);
    if ($id <= 0) {
      return result([], 2, '业务参数非法');
    }
    $eax = table('FamilyMember', 'rydb.websms')->where(['ID' => $id])->update(['IsPass' => 1, 'UpdateTime' => new Expression('GETDATE()')]);
    return result([], 0);
  }
  /**
   *  @brief : 赠送群货币
   *  @return: JSON
   *  @detail: 
   */
  public function zenggoldAction() {
    if (!$this->request->isPost()) {
      return result([], 1, '非法请求');
    }
    $id = $this->request->param('id/d', 0);
    if ($id <= 0) {
      return result([], 2, '业务参数非法');
    }
    $gold = $this->request->param('gold/d', 0);
    $eax = table('FamilyMember', 'rydb.websms')->where(['ID' => $id])->setInc('Gold', $gold);
    return result([], 0);
  }

   /**
   *  @brief : 群规则管理
   *  @return: page
   *  @detail: 
   */

  public function RuledataAction(){
    $order = [];
    $GAME_KIND  = GetGameKind();
    $CHANNELS   = $this->GetAdminChannel();
    ////////////////////////////////////////////////////////////////////////////
    $channel = $this->request->param('channel/d', -1);
    if ($channel > 0 && array_key_exists($channel, $CHANNELS)) {
      $conds['a.Channel'][] = ['IN', array_keys($CHANNELS)];
      $conds['a.Channel'][] = ['EQ', $channel];
    } else {
      $conds['a.Channel'] = ['IN', array_keys($CHANNELS)];
    }
    //////////////////////////////////////////////////////
    $kind = $this->request->param('kind/d', -1);
    if ($kind > 0 && array_key_exists($kind, $GAME_KIND)) {
      $conds['a.KindID'] = $kind;
    }
    //////////////////////////////////////////////////////

    $paytype = $this->request->param('Paytype/d', -1); // 支付方式
    if ($paytype >= 0 && in_array($paytype, [1, 2])) {
      $conds['a.PayType'] = $paytype;
    }

    //////////////////////////////////////////////////////
    $search = $this->request->param('search/s', '', 'trim');
    if (!empty($search)) {
      if (is_numeric($search)) {
        $search = $this->request->param('search/d', 0);
        $conds['a.UserID|c.GameID'] = $search;
      } else {
        $conds['c.NickName'] = ['LIKE', "%{$search}%"];
      }
    }
    //////////////////////////////////////////////////////
    $code1 = $this->request->param('code1/d', 0);
    if ($code1 > 0) {
      $conds['a.GroupID'] = $code1;  // 六位群号
    }
    $code3 = $this->request->param('code3/d', 0); // 群主GameID
    if ($code3 > 0) {
      $conds['e.GameID'] = $code3;
    }
      $code4 = $this->request->param('code4/d', 0); // 群号
      if ($code4 > 0) {
          $conds['a.GroupID'] = $code4;
      }
    //////////////////////////////////////////////////////
    $orderMap = [
      'A' => 'ID',
      'B' => 'Channel',
      'C' => 'KindID',
      'D' => 'GroupID',
      'E' => 'GameID',
      'F' => 'FGameID',
      'H' => 'CreateTime',
      'I' => 'MemberNumb',
      'J' => 'TableNumb',
      'K' => 'PayType',
    ];
    $this->orderField = array_key_exists($this->orderField, $orderMap) ? $this->orderField : 'H';
    $order[$orderMap[$this->orderField]] = $this->orderDirection;
    $codes['a.Code'] = $code1;
    $list = table('CYRecordDB.dbo.RecordProxyGameRule a', 'rydb.record')->field([
      'a.*', 'd.UserRight', 'd.IsBlack', 'd.IsPass',
      'b.AUID' => 'FUserID', 
      'b.Code', 'c.GameID', 'c.NickName', 'c.Sex','b.FamilyType',
      'c.AccountsType', "ISNULL(c.AccountImgUrl, '')" => 'Avatar',
      'c.Accounts', 'c.Compellation', 'c.PassPortID', 'c.RegisterMobile', 'c.RegisterDate',
      'c.RegisterIP', 'c.GameLogonCount', 'c.LastLogonDate', 'c.LastLogonIP',
      'e.GameID' => 'FGameID', 'e.AccountsType' => 'FAccountsType',
      '(CASE WHEN LEN([e].[Compellation]) = 0 THEN [e].[NickName] ELSE [e].[Compellation] END)'=>'FCompellation',
      'ISNULL(e.SpreaderID, 0)' => 'AUserID', 
      '(CASE WHEN a.UserID = b.AUID THEN 1 ELSE 0 END)' => 'IsBoss',
    ])
    //群信息
    ->join('CYWebSMSDB.dbo.Family b', 'b.Code = a.GroupID', 'LEFT')
    // 成员
    ->join('CYBasicDB.dbo.AccountsInfo c', 'c.UserID = a.UserID', 'LEFT')
    //属性
    ->join('CYWebSMSDB.dbo.FamilyMember d', 'd.MemberUID = a.UserID', 'LEFT')
    // 群主
    ->join('CYBasicDB.dbo.AccountsInfo e', 'e.UserID = a.UserID AND e.Channel = a.Channel', 'LEFT')
    //渠道信息
    ->join('CYBasicDB.dbo.ChannelConfig k', 'k.ID = c.Channel', 'LEFT')
    //附属信息
    ->join('CYBasicDB.dbo.AccountsGameCurrency f', 'f.UserID = a.UserID', 'LEFT')
    ->where($conds)->order($order)->paginate()->each(function( $item, $key){
      $item['RuleData'] = json_decode($item['RuleData'],true);
      return $item;
      });
    
    ////////////////////////////////////////////////////////////////////////////
    return $this->fetch('', [
      'CHANNELS'  => $CHANNELS,
      'channel'   => $channel,
      'GAME_KIND' => $GAME_KIND,
      'kind'    => $kind,
      'code1'   => $code1 === 0 ? -1 : $code1,
      'code3'   => $code3 === 0 ? '' : $code3,
      'list'    => $list,
      'search'  => $search,
      'PayType'   => $paytype,
    ]);

  }



}
